package com.qiniuyun.backai.controller;

import com.qiniuyun.backai.common.BaseResponse;
import com.qiniuyun.backai.common.ErrorCode;
import com.qiniuyun.backai.common.ResultUtils;
import com.qiniuyun.backai.exception.BusinessException;
import com.qiniuyun.backai.exception.ThrowUtils;
import com.qiniuyun.backai.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import java.util.List;
import com.qiniuyun.backai.model.vo.MessageVO;

/**
 * 对话控制器
 * @author 王龙飞
 * @since 2025-09-24
 */
@Slf4j
@RestController
@RequestMapping("/chat")
public class ChatController {
    @Autowired
    private ChatClient chatClient;
    @Autowired
    private ChatService chatService;
    @Autowired
    private ChatMemory chatMemory;

    //todo 用包装类返回会报错
    /**
     * 增加会话
     * @param prompt
     * @param chatId
     * @return
     */
    @GetMapping(value = "/add", produces = "text/html;charset=utf-8")
    public Flux<String> addChat(@RequestParam  String role, String prompt, String chatId) {
        //判空
        ThrowUtils.throwIf((chatId == null || prompt == null), ErrorCode.PARAMS_ERROR);
        try {
            log.info("系统角色为{}",role);
            Flux<String> content = chatClient
                    .prompt()
                    .user(prompt)// 传入user提示词
                    .system("你是现在是一名"+role)
                    .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
                    .stream()
                    .content();
            return content;
        } catch (Exception e) {
            log.info(String.format("异常为 {}", e));
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }

    }

    /**
     * 根据某个会话id获取历史对话
     *
     * @param chatId
     * @return
     */
    @PostMapping("/{chatId}")
    public BaseResponse<List<MessageVO>> getChatHistory(@PathVariable("chatId") String chatId) {
        //判断参数是否为空
        ThrowUtils.throwIf(chatId==null,ErrorCode.PARAMS_ERROR);
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (messages == null) {
            return ResultUtils.success(List.of());
        }
        return ResultUtils.success(messages.stream().map(MessageVO::new).toList());
    }

    /**
     * 根据chatId删除会话记录
     * @param chatId
     * @return
     */
    @DeleteMapping("/delete/{chatId}")
    public BaseResponse deleteChat(@PathVariable("chatId") String chatId) {
        //判断参数是否为空
        ThrowUtils.throwIf(chatId==null,ErrorCode.PARAMS_ERROR);
        chatService.deleteByConvId(chatId);
        return ResultUtils.success(null);
    }

}
